/**
 * @author David Milne
 */

function QueryResultsTray() {
	logDebug("QueryResultsTray created");
	
	this.tabPane ;
	
	this.docNodes ;
	
	this.prompt ;
	this.loading ;
	this.contentArea ;
	this.currPageNum ;
	this.queryResults ;
	
	this.xmlHttp ;
	this.xmlHttp2 ;
	
	this.docsToOpen ;
}

QueryResultsTray.prototype.init = queryResultsTray_init ;
QueryResultsTray.prototype.resize = queryResultsTray_resize ;
QueryResultsTray.prototype.setLoading = queryResultsTray_setLoading ;

QueryResultsTray.prototype.tabSelectionChanged = queryResultsTray_tabSelectionChanged ;
QueryResultsTray.prototype.handleQueryChanged = queryResultsTray_handleQueryChanged ;
QueryResultsTray.prototype.requestDocumentIds = queryResultsTray_requestDocumentIds ;
QueryResultsTray.prototype.processDocIdResponse = queryResultsTray_processDocIdResponse ;
QueryResultsTray.prototype.requestDocumentTitles = queryResultsTray_requestDocumentTitles ;
QueryResultsTray.prototype.processDocTitlesResponse = queryResultsTray_processDocTitlesResponse ;
QueryResultsTray.prototype.requestDocumentSurrogates = queryResultsTray_requestDocumentSurrogates ;
QueryResultsTray.prototype.processDocSurrogatesResponse = queryResultsTray_processDocSurrogatesResponse ;
QueryResultsTray.prototype.animateDocumentOpening = queryResultsTray_animateDocumentOpening ;

QueryResultsTray.prototype.requestQueryScore = queryResultsTray_requestQueryScore ;
QueryResultsTray.prototype.processQueryScoreResponse = queryResultsTray_processQueryScoreResponse ;



function queryResultsTray_init() {
	try {
		this.id = "queryResultsTray" ;
		this.className = "tray" ;
		
		var title = document.createElement("img") ;
		title.className = "title" ;
		title.src = "images/queryResults.gif" ;
		this.appendChild(title) ;
		
		var tl = document.createElement("div") ;
		tl.className = "border_tl" ;
		this.appendChild(tl) ;
		
		var tr = document.createElement("div") ;
		tr.className = "border_tr" ;
		this.appendChild(tr) ;
		
		var bl = document.createElement("div") ;
		bl.className = "border_bl" ;
		this.appendChild(bl) ;
		
		var br = document.createElement("div") ;
		br.className = "border_br" ;
		this.appendChild(br) ;
		
		this.loading = document.createElement("div") ;
		this.loading.className = "loading" ;
		this.appendChild(this.loading) ;
		this.setLoading(false) ;
		
		this.prompt = document.createElement("div") ;
		this.prompt.className = "prompt" ;
		this.appendChild(this.prompt) ;

		this.tabPane = document.applyInherit(document.createElement('div'), new TabPane()) ;
		this.tabPane.init(new Function("koru.queryResultsTray.tabSelectionChanged()"), null, RIGHT) ;
		this.appendChild(this.tabPane) ;

		
		this.contentArea = document.createElement("div") ;
		this.contentArea.className = "contentArea" ;
		this.contentArea.innerHTML = "" ;
		this.appendChild(this.contentArea) ;
		
		this.score_tooltip = document.createElement("div") ;
		this.score_tooltip.id = "score_tooltip" ;
		this.score_tooltip.onmouseout = new Function("event", "if (isMouseLeaveOrEnter(event, this)) koru.queryResultsTray.score_tooltip.style.display = 'none'") ;
		this.appendChild(this.score_tooltip) ;
		
		/*
		for (var i=0 ; i < 10 ; i++) {
			var tab = document.createElement("li") ;
			tab.className = "tab_deselected" ;
			tab.innerHTML = "<span>" + (i+1) + "</span>" ;
			
    		tab.onclick = new Function("koru.queryResultsTray.selectPage(" + i + ") ;") ;
   			this.tabs.appendChild(tab) ;
   		}
		
		this.selectPage(0) ;
		*/
	} catch ( e ) { 
		logError("queryResultsTray.init.error: " + e ); 
		throw (e) ;
	}
} 
  
function queryResultsTray_resize(width, height) {
	try {
		this.style.width = width-4 + "px" ;
		this.style.height = height-4 + "px" ;
		
		this.contentArea.style.width = width-24 + "px" ;
		this.contentArea.style.height = height-74 + "px" ;
		
		this.tabPane.resize(width - 200) ;
	} catch (e) {
		logError("queryResultsTray.resize.error: " + e) ;
		throw (e) ;
	}
}

function queryResultsTray_setLoading(loading) {
	if (loading==true) 
		this.loading.style.display = "" ;
	else
		this.loading.style.display = "none" ;
}

function queryResultsTray_handleQueryChanged() {
	try {
		logDebug("query changed") ;
		this.contentArea.innerHTML = "" ;
		this.requestDocumentIds() ;
	} catch (e) {
		logError("queryResultsTray.handleQueryChanged.error: " + e) ;
		throw (e) ;
	}
}

function queryResultsTray_tabSelectionChanged() {
	try {
		
		this.contentArea.innerHTML = "" ;
		
		var pageNum = this.tabPane.getTabIndexForId(this.tabPane.currTabId) ;
					
		var startIndex, endIndex ;
  
  		startIndex = pageNum * 10 ;
  		if (startIndex + 10 > this.docNodes.length - 1)
   			endIndex = this.docNodes.length ;
  		else
   			endIndex = startIndex + 10 ;
   
  		var promptText = "Documents <em>" + (startIndex + 1) + "</em>-<em>" + endIndex + "</em>" ;
  		if (this.docNodes.length >= 100) 
   			promptText = promptText + " of over <em>100</em>" ;
  		else
   			promptText = promptText + " of <em>" + this.docNodes.length + "</em>" ;
		
		this.prompt.innerHTML = promptText ;
				
		var visibleDocs = new Array() ;
  		for (var i = startIndex ; i < endIndex ; i++)
   			visibleDocs.push(this.docNodes[i]) ;
			
		this.requestDocumentTitles(visibleDocs) ;
	} catch (e) {
		logError("queryResultsTray.tabSelectionChanged.error: " + e) ;
		throw (e) ;
	}
}

function queryResultsTray_requestDocumentIds() {
	try {
  		var queryText = koru.searchBox.getCurrentQuery() ;
		this.setLoading(true) ;
  
  		if (queryText == "")
   			return ;
   
  		//this.setLoading(true) ;
  
  		logDebug("Querying: " + queryText) ;   

  		var maxdocs = newElementAtt('param', '', new Array('name', 'value'), new Array('maxDocs', '100') ) ;
 		var hitsPerPage = newElementAtt('param', '', new Array('name', 'value'), new Array('hitsPerPage', '100') ) ;
		//var level = newElementAtt('param', '', new Array('name', 'value'), new Array('level', 'Doc') ) ;
  		//var indexValue = newElementAtt('param', '', new Array('name', 'value'), new Array('index', 'TX') ) ;
  		var matchMode = newElementAtt('param', '', new Array('name', 'value'), new Array('matchMode', 'some') ) ;
  		var query = newElementAtt1('param', queryText, 'name', 'query') ;
  
  		//var query = newElementAtt('param', '', new Array('name', 'value'), new Array('query', queryText) ) ;
  		//var caseValue = newElementAtt('param', '', new Array('name', 'value'), new Array('case', '1') ) ;
  		//var sortBy = newElementAtt('param', '', new Array('name', 'value'), new Array('sortBy', '1') ) ;
  		stem = newElementAtt('param', '', new Array('name', 'value'), new Array('stem', '1') ) ;

		var paramList = newElement('paramList', maxdocs + hitsPerPage + matchMode + stem + query);
  		//var paramList = newElement('paramList', maxdocs + level + matchMode + query + indexValue + caseValue + sortBy + stem); 
  		var request = newElementAtt('request', paramList, new Array('lang', 'to', 'type', 'uid'), new Array('en',collection + '/TextQuery', 'process', '1'  ) );
  		var message = newElement('message', request );
  		var soapMessage = messageToSOAP(message);
   
  		this.xmlHttp = XmlHttp.create();
  		this.xmlHttp.open("POST", "http://" + serverPath + "/services/localsite", true);
  		this.xmlHttp.onreadystatechange = new Function("koru.queryResultsTray.processDocIdResponse() ; ") ;
   
  		this.xmlHttp.setRequestHeader("SOAPAction", "\"\"");
  		this.xmlHttp.setRequestHeader("Content-Type", "Content-Type: text/xml; charset=utf-8");
   
   		//logDebug(message) ;
  		this.xmlHttp.send(soapMessage);
 	} catch (e) {
  		logError("queryResultsTray.requestDocumentIds.error: " + e ); 
  		throw (e) ; 
 	}
}

function queryResultsTray_processDocIdResponse() {
	try{
		if (this.xmlHttp.readyState == 4) {
			//logDebug(this.xmlHttp.responseXML.xml) ;
			
  			this.currPageNum = -1 ;
   			this.docNodes = this.xmlHttp.responseXML.getElementsByTagName('documentNode');
   			logDebug(this.docNodes.length + " documents found") ;
 			this.tabPane.clear() ;
			
			if (this.docNodes.length < 1) {
				this.setLoading(false) ;
				this.contentArea.innerHTML = "" 
				this.prompt.innerHTML = "<em>0</em> documents found" ;
				return ;
			}
   
   			var tabCount ;
   			if (this.docNodes.length == 1) 
				tabCount = 1 ;
			else
				tabCount = (this.docNodes.length-1) / 10 ;
		
			for (var i=0 ; i < tabCount ; i++) {
				this.tabPane.addTab(i+1, i+1) ;
   			}
			
   			this.tabPane.selectTab(1) ;
			this.requestQueryScore(koru.searchBox.getCurrentQuery(), this.docNodes) ;
			
		}
  	} catch(e) {
  		logError("queryResultsTray.processDocIdResponse.error: " + e ); 
  		throw (e) ;
	}
}

function queryResultsTray_requestQueryScore(queryText, documentNodes) {
	try {
		
   		var dHashes = "" ;
     
  		for (var i=0; i < documentNodes.length; i++) {
  			var documentNode = documentNodes[i];
  			if (isElement(documentNode)) {
  				dHashes = dHashes + documentNode.getAttribute('nodeID') ;
    			if (i < documentNodes.length - 1) 
     				dHashes = dHashes + "," ;
  			}
  		}	
		
		var docHashes = newElementAtt('param', '', new Array('name', 'value'), new Array('docHashes', dHashes) ) ;
  		var query = "<query>" + koru.searchBox.getCurrentQuery() + "</query>" ;
        var taskId = newElementAtt('param', '', new Array('name', 'value'), new Array('taskId', koruGame.task_id) ) ; 
		var player = newElementAtt('param', '', new Array('name', 'value'), new Array('playerName', koruGame.player) ) ;
		
		var paramList = newElement('paramList', docHashes + taskId + player);
  		var request = newElementAtt('request', paramList + query, new Array('lang', 'to', 'type', 'uid'), new Array('en',collection + '/GetQueryScore', 'process', '1'  ) );
  		var message = newElement('message', request );
  		var soapMessage = messageToSOAP(message);
   
  		this.xmlHttp2 = XmlHttp.create();
  		this.xmlHttp2.open("POST", "http://" + serverPath + "/services/localsite", true);
  		this.xmlHttp2.onreadystatechange = new Function("koru.queryResultsTray.processQueryScoreResponse() ; ") ;
   
  		this.xmlHttp2.setRequestHeader("SOAPAction", "\"\"");
  		this.xmlHttp2.setRequestHeader("Content-Type", "Content-Type: text/xml; charset=utf-8");
   
   		logDebug("Score Request: " + message) ;
  		this.xmlHttp2.send(soapMessage);
  	} catch(e) {
  		logError("queryResultsTray.requestQueryScore.error: " + e ); 
  		throw (e) ;
	}	
}

function queryResultsTray_processQueryScoreResponse() {
	try {
  		if (this.xmlHttp2.readyState == 4) {
			logDebug(this.xmlHttp2.responseXML.xml) ;
			
			var queryScore = this.xmlHttp2.responseXML.getElementsByTagName('queryScore')[0];
		
			if (queryScore != null) {
				var score = queryScore.getAttribute("score") ;
				var ranking = queryScore.getAttribute("ranking") ;
				
				var dr = Number(queryScore.getAttribute("docs_returned")) ;
				var rdr = Number(queryScore.getAttribute("rel_docs_returned")) ;
				var rdt = Number(queryScore.getAttribute("rel_docs_total")) ;
			
				koruGame.postQueryScore(koru.searchBox.getCurrentQuery(), score, ranking, dr, rdr, rdt) ;
				
				var recentQueries = this.xmlHttp2.responseXML.getElementsByTagName('recentQueries')[0];
				var bestQueries = this.xmlHttp2.responseXML.getElementsByTagName('bestQueries')[0];
			
				koru.searchBox.recentQueries = recentQueries ;
				koru.searchBox.bestQueries = bestQueries ;
			}
		}
	} catch(e) {
		logError("queryResultsTray.requestQueryScore.error: " + e ); 
  		throw (e) ;
	}
}

function queryResultsTray_requestDocumentTitles(documentNodes) {
	try {
		this.setLoading(true) ;
    	var docIDArray = new Array();
    
   		for (var i=0; i < documentNodes.length; i++) {
    		var documentNode = documentNodes[i];
    		if (isElement(documentNode)) {
    			docIDArray[i] = documentNode.getAttribute('nodeID');
    		}
    	}
   
    	var docsList = '';
    	for (var i=0; i < docIDArray.length; i++) {
    		docsList += newElementAtt1('documentNode', '', 'nodeID', docIDArray[i]);
    	}
	
    	var docNodeList = newElement('documentNodeList', docsList);
    	var param = newElementAtt('param', '', new Array('name', 'value'), new Array('metadata', 'Title') );
    	var paramList = newElement('paramList', param);
	   	var request = newElementAtt('request', paramList + docNodeList, new Array('lang', 'to', 'type', 'uid'), new Array('en',collection + '/DocumentMetadataRetrieve', 'process', '1'  ) );
    	var message = newElement('message', request ); 
    	var soapMessage = messageToSOAP(message);
 
  		this.xmlHttp = XmlHttp.create();
  		this.xmlHttp.open("POST", "http://" + serverPath + "/services/localsite", true);
  		this.xmlHttp.onreadystatechange = new Function("koru.queryResultsTray.processDocTitlesResponse() ; ") ;
   
  		this.xmlHttp.setRequestHeader("SOAPAction", "\"\"");
  		this.xmlHttp.setRequestHeader("Content-Type", "Content-Type: text/xml; charset=utf-8");
  
  		this.xmlHttp.send(soapMessage);
 	} catch (e) {
  		logError("queryResultsTray.requestDocumentIds.error: " + e ); 
  		throw (e) ; 
	}
}

function queryResultsTray_processDocTitlesResponse() {
	try {
  		if (this.xmlHttp.readyState == 4) {
			
			this.queryResults = new Array() ;
			
			var docs = this.xmlHttp.responseXML.getElementsByTagName('documentNode');
   
   			for (var i=0; i < docs.length && i < 10; i++) {
 			
				if (isElement(docs[i])) {
     
     				var docTitle, docHash ;
     
     				var metadata = docs[i].getElementsByTagName('metadata') ;
					
    				if (metadata.length > 0)
      					docTitle = getNodeText(metadata[0]) ;
					else
						docTitle = "Document title unknown" ;
						
					if (docTitle == "")
						docTitle = "Document title unknown" ;	
						
     				hash = docs[i].getAttribute('nodeID') ;
					
					var queryResult = document.applyInherit(document.createElement('div'), new QueryResult()) ;
					queryResult.init(docTitle, hash, i) ;
  					this.contentArea.appendChild(queryResult) ;
					this.queryResults.push(queryResult) ;
    			}
   			}
			this.contentArea.scrollTop = 0 ;
			this.requestDocumentSurrogates(docs) ;
		}	
	} catch (e) {
		logError("queryResultsTray.processDocTitlesResponse.error: " + e ); 
  		throw (e) ; 
	}
}

function queryResultsTray_requestDocumentSurrogates(documentNodes) {
	try {
  		if (documentNodes.length == 0)
   			return ;
 
  		var dHashes = "" ;
     
  		for (var i=0; i < documentNodes.length; i++) {
  			var documentNode = documentNodes[i];
  			if (isElement(documentNode)) {
  				dHashes = dHashes + documentNode.getAttribute('nodeID') ;
    			if (i < documentNodes.length - 1) 
     				dHashes = dHashes + "," ;
  			}
  		}	
  
  		var taskId = newElementAtt('param', '', new Array('name', 'value'), new Array('taskId', koruGame.task_id) ) ; 
  		var docHashes = newElementAtt('param', '', new Array('name', 'value'), new Array('docHashes', dHashes) ) ;
  		var wordLimit = newElementAtt('param', '', new Array('name', 'value'), new Array('wordLimit', 25) ) ;
  		var query = "<query>" + koru.searchBox.getCurrentQuery() + "</query>" ;
  
  		var paramList = newElement('paramList', taskId + docHashes + wordLimit) ;
  		var request = newElementAtt('request', paramList + query, new Array('lang', 'to', 'type', 'uid'), new Array('en', collection + '/GetSurrogates', 'process', '1'  ) );
  		var message = newElement('message', request );
  		var soapMessage = messageToSOAP(message);
  
  		this.xmlHttp = XmlHttp.create();
  		this.xmlHttp.open("POST", "http://" + serverPath + "/services/localsite", true);
  		this.xmlHttp.onreadystatechange = new Function("koru.queryResultsTray.processDocSurrogatesResponse() ; ") ;
   
  		this.xmlHttp.setRequestHeader("SOAPAction", "\"\"");
  		this.xmlHttp.setRequestHeader("Content-Type", "Content-Type: text/xml; charset=utf-8");
     
  		this.xmlHttp.send(soapMessage);
		logDebug(soapMessage) ;
		
 	} catch (e) {
  		logError("queryResultsTray.requestDocumentIds.error: " + e ); 
  		throw (e) ; 
 	}
}


function queryResultsTray_processDocSurrogatesResponse() {
	try{
		if (this.xmlHttp.readyState == 4) { 
			var docs = this.xmlHttp.responseXML.getElementsByTagName('DocumentSurrogate') ;
   
   			this.docsToOpen = new Array() ;
   
   			for (var i=0; i < docs.length; i++) {
   				var doc = docs[i];
    			if (isElement(doc)) {    
     				var hash = doc.getAttribute('hash') ;
     				var numTerms = doc.getAttribute('numTerms') ;
					var relevance = doc.getAttribute('relevance') ;
					var id = doc.getAttribute('id') ;
					
     
     				var snippet = doc.getElementsByTagName('Snippet')[0] ;
					
					this.queryResults[i].setDetails(snippet.getAttribute("text"), numTerms) ;
					
					koruGame.documentLocated(id, relevance) ;
					
					if (relevance == 2 && highlightMatches) {
						this.queryResults[i].style.backgroundColor = "#def392" ;
					}
					
					//if (relevance == 1 && highlightMatches) {
					//	this.queryResults[i].style.backgroundColor = "rgb(200,200,200)" ;
			
					//}
					
					//if (relevance == 2 && openMatches) {
					//	this.docsToOpen.push(this.queryResults[i]) ;
					//}
				}
			}
						
			if (openMatches && this.docsToOpen.length > 0)
					this.animateDocumentOpening() ;
					
			this.setLoading(false) ;
		}
	} catch (e) {
		logError( "queryResultsTray.processDocSurrogatesResponse.error: " + e ); 
  		throw (e) ; 
 	}
}

function queryResultsTray_animateDocumentOpening() {
	try{
		queryResult = this.docsToOpen[0] ;
		this.docsToOpen.splice(0,1) ;
		
		//queryResult.flash() ;
		queryResult.select() ;
		
		if (this.docsToOpen.length > 0)
			setTimeout(new Function("koru.queryResultsTray.animateDocumentOpening()"), 1000) ;
	} catch (e) {
		logError( "queryResultsTray.animateDocumentOpening.error: " + e ); 
  		throw (e) ; 
 	}	
}